#include "Log.h"
#include "stddef.h"
#define  CCP_LOGGER_EMBEDDED 1
#include "LogServer.h"
#include "LoggerLib.h"

bool UnicodeToAnsi(const TCHAR* unicodeStr, char* ansiChar, int maxLen)
{
	bool res = false;

	if (unicodeStr && ansiChar)
	{		
		size_t numChar = wcslen(unicodeStr)+1;

		if (maxLen > numChar * 2)
		{			
			// Convert to ANSI.
			res = WideCharToMultiByte(CP_ACP, 0, unicodeStr, numChar, ansiChar, maxLen, NULL, NULL) != 0;
		}
	}

	return res;
}


LOGOBJECT("PrimeGame", "Main", MAIN)

void Logger::Startup(HINSTANCE windowInstance)
{
	LOGINITIALIZE(windowInstance, "EVE");

	bool res = Log__IsLogging();

	LOGMAIN(LGINFO, "PrimeGame log device initialized");
}

void Logger::Shutdown()
{
	LOGTERMINATE();
}

#define ANSI_BUFFER_LEN 512

void Logger::Log(const TCHAR* data, ELogLevel level, const TCHAR* channel)
{
	if (!LogIsLogging())
		return;

	TLOGFLAG flags[LOG_Error + 1] = {LGINFO, LGWARN, LGERR};

	TCHAR msg[LOG_MAXMESSAGE+1];
	const TCHAR* src;
	TCHAR* dst;

	static char ansiBuffer[ANSI_BUFFER_LEN];

	for (src = data, dst = msg; ; )
	{
		// Fill 'msg' and flush on line-breaks, max message size or end of string.
		if (*src == TEXT('\r') || *src == TEXT('\n') || dst - msg >= LOG_MAXMESSAGE-1 || *src == TEXT('\0'))
		{
			// Flush 'msg' if applicable
			if (dst != msg)
			{
				*dst = TEXT('\0');
				if (UnicodeToAnsi(msg, ansiBuffer, ANSI_BUFFER_LEN))
				{
					LOGMAIN(flags[level], "%s", ansiBuffer);
				}				
			}

			// Skip over CRLF's
			while (*src == TEXT('\r') || *src == TEXT('\n'))
				src++;

			// Quit if all is done
			if (*src == TEXT('\0'))
				break;

			// Start fill buffer again and continue logging out
			wcscpy_s(msg, TEXT("->\t"));
			dst = msg + 3;
		}

		*dst++ = *src++;
	}
}

Logger& Logger::Singleton()
{
	static Logger theLogger;
	return theLogger;
}